﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeChatParking.Core;

namespace WeChatParking.Web.Controllers
{
    public class UnionPayController : Controller
    {
        public ActionResult Index()
        {
            return Content(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        }
        #region 车辆状态同步  通过
        /// <summary>
        /// 车辆绑定/解绑，无感支付开通/关闭通知。智慧通行平台通过调用此接口，将车辆绑定/解绑以及无感支付开通/关闭信息通知给运行商平台。
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult carStatus()
        {

            System.IO.Stream stream = Request.InputStream;
            string json = string.Empty;
            if (stream.Length != 0)
            {
                System.IO.StreamReader streamReader = new System.IO.StreamReader(stream);
                json = streamReader.ReadToEnd();
            }
            WeChatParking.Core.Payment.UnionPay.carStatus model = (WeChatParking.Core.Payment.UnionPay.carStatus)JsonConvert.DeserializeObject(json, typeof(WeChatParking.Core.Payment.UnionPay.carStatus));
            int i = json.IndexOf("signature") - 2;
            string data = json.Substring(0, i);
            data += "}";
            WeChatParking.Core.Payment.UnionPay.Responses res = new WeChatParking.Core.Payment.UnionPay.Responses();
            try
            {
                LogHelper.Info(json, "无感车辆状态同步");
                LogHelper.Info(data, "无感车辆状态同步--签名数据");
                bool isSign = WeChatParking.Core.Payment.UnionPay.UnionPayCommon.CheckSign2(data, WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey, model.signature);

                if (isSign)
                {

                    string sql = String.Format("carBrand ='{0}' AND status=1 ", model.data.plateNumber);
                    var bll = new Core.BLL.CarRecord();
                    var InOutmodel = bll.Get(sql, "inTime", true).FirstOrDefault();
                    if (InOutmodel == null)
                    {
                        res.resultCode = "1007";
                        res.message = "车辆不在场内";
                        return Content(JsonConvert.SerializeObject(res));
                    }
                    Entity.Car_Plate carModel = new Entity.Car_Plate();
                    carModel.Car_plate = model.data.plateNumber;
                    carModel.signNo = String.IsNullOrWhiteSpace(model.data.signNo) ? "" : model.data.signNo;
                    carModel.status = model.data.status;
                    carModel.statusDescription = model.data.statusDescription;
                    if (new WeChatParking.Core.BLL.Car_Plate().UnionPayCar_Plate(carModel))
                    {
                        res.resultCode = "0000";
                        res.message = "成功";
                    }
                    else
                    {
                        res.resultCode = "1007";
                        res.message = "车辆不在场内";
                    }
                }
                else
                {
                    res.resultCode = "1004";
                    res.message = "签名失败";
                }
            }
            catch (Exception ex)
            {
                res.resultCode = "1003";
                res.message = "系统异常";
                LogHelper.Error(ex, "无感车辆状态同步");
            }
            string qu = JsonConvert.SerializeObject(res);
            LogHelper.Info(qu, "无感车辆状态同步返回");
            return Content(qu);
        }
        #endregion
        #region 订单  通过
        /// <summary>
        /// 用户在智慧通行平台上完成支付后，智慧通行平台通过调用此接口将支付结果返回给运营商。
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult payResult(WeChatParking.Core.Payment.UnionPay.PayResult model)
        {
            LogHelper.Info(JsonConvert.SerializeObject(model), "无感完成支付后");
            WeChatParking.Core.Payment.UnionPay.Responses res = new WeChatParking.Core.Payment.UnionPay.Responses();
            try
            {
                Core.BLL.PrepaidOrder bll = new Core.BLL.PrepaidOrder();
                if (model.data.payStatus == 0)
                {
                    bll.HandleOrder(model.data.orderId, Convert.ToDecimal(model.data.payAmount) / 100, model.data.upOrderId, Entity.Enums.PayType.UnionPay);
                    res.resultCode = "0000";
                    res.message = "成功";
                    var retryModel = new WeChatParking.Core.BLL.retry().Get(String.Format(" order_id='{0}' and type=0 and status=0", model.data.orderId)).FirstOrDefault();
                    if (retryModel != null)
                    {
                        retryModel.status = 1;
                        new WeChatParking.Core.BLL.retry().Update(retryModel);
                    }
                    //查询出是否是已经无效的数据，是就退款
                    var payRetryModel = new WeChatParking.Core.BLL.retry().Get(String.Format(" order_id ='{0}' AND type=4 ", model.data.orderId)).FirstOrDefault();
                    if (payRetryModel != null)
                    {
                       var order= bll.GetOrder(model.data.orderId);
                        string request = "";
                        try
                        {
                            new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundBill(order.car_no, model.data.payAmount, model.data.orderId, model.data.orderId, out request);
                            payRetryModel.status = 1;
                            new WeChatParking.Core.BLL.retry().Update(payRetryModel);
                        }
                        catch (Exception ex)
                        {
                            LogHelper.Error(ex, "无感完成支付后退款异常");
                        }
                    }
                }
                else if (model.data.payStatus == 1)
                {
                    var ord = bll.GetOrder(model.data.orderId);
                    if (ord != null)
                    {
                        ord.order_status = 2;
                        ord.pay_status = 1;
                        bll.Update(ord);
                        //下发
                    }
                    res.resultCode = "0000";
                    res.message = "成功";
                }
                else if (model.data.payStatus == 2)
                {
                    var ord = bll.GetOrder(model.data.orderId);
                    if (ord != null)
                    {
                        ord.order_status = 4;
                        ord.pay_status = 1;
                        ord.pay_note = "智慧通行支付失败";
                        bll.Update(ord);
                    }
                    res.resultCode = "0000";
                    res.message = "成功";
                }
                else
                {
                    res.resultCode = "1002";
                    res.message = "支付结果通知状态码异常";
                }
            }
            catch (Exception ex)
            {
                res.resultCode = "1003";
                res.message = "系统异常";
                LogHelper.Error(ex, "无感完成支付后");
            }
            return Content(JsonConvert.SerializeObject(res));
        }
        /// <summary>
        /// 申请退款后，智慧通行平台通过调用此接口将退款结果返回给运营商。
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult refundResult(WeChatParking.Core.Payment.UnionPay.RefundResult model)
        {
            LogHelper.Info(JsonConvert.SerializeObject(model), "无感完成退款后");
            //退款完成单
            //修改订单状态
            WeChatParking.Core.Payment.UnionPay.Responses res = new WeChatParking.Core.Payment.UnionPay.Responses();
            try
            {
                Core.BLL.PrepaidOrder bll = new Core.BLL.PrepaidOrder();
                if (model.data.payStatus == 4)
                {
                    bll.HandleOrder(model.data.orderId, Convert.ToDecimal(model.data.refundAmount) / 100, model.data.upRefundId, Entity.Enums.PayType.UnionPay, true);
                    res.resultCode = "0000";
                    res.message = "成功";
                    var retryModel = new WeChatParking.Core.BLL.retry().Get(String.Format(" order_id='{0}' and type=1 and status=0", model.data.orderId)).FirstOrDefault();
                    if (retryModel != null)
                    {
                        retryModel.status = 1;
                        new WeChatParking.Core.BLL.retry().Update(retryModel);
                    }
                }
                else if (model.data.payStatus == 3)
                {
                    var ord = bll.GetOrder(model.data.orderId);
                    if (ord != null)
                    {
                        ord.order_status = 2;
                        ord.pay_status = 1;
                        bll.Update(ord);
                    }
                    res.resultCode = "0000";
                    res.message = "成功";
                }
                else if (model.data.payStatus == 5)
                {
                    var ord = bll.GetOrder(model.data.orderId);
                    if (ord != null)
                    {
                        ord.order_status = 4;
                        ord.pay_status = 1;
                        ord.pay_note = "无感支付退款失败";
                        bll.Update(ord);
                    }
                    res.resultCode = "0000";
                    res.message = "成功";
                }
                else
                {
                    res.resultCode = "1002";
                    res.message = "支付结果通知状态码异常";
                }
                res.resultCode = "0000";
                res.message = "成功";
            }
            catch (Exception ex)
            {
                res.resultCode = "1003";
                res.message = "系统异常";
                LogHelper.Error(ex, "无感完成退款后");
            }
            return Content(JsonConvert.SerializeObject(res));
        }
        #endregion
        #region 主动缴费  通过
        /// <summary>
        /// 当用户车辆驶入停车场后，可以通过此接口查询用户的停车费信息。
        /// </summary>
        /// <param name="plateNumber">车牌号</param>
        /// <param name="appId">运营商给智慧通行平台颁发的商户号。</param>
        /// <param name="pageNo"></param>
        /// <param name="count"></param>
        /// <param name="signature"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult queryFee(string plateNumber, string appId, string pageNo, int count, string signature)
        {
            string data = "{\"appId\":\"" + appId + "\",\"count\":" + count.ToString() + ",\"pageNo\":" + pageNo.ToString() + ",\"plateNumber\":\"" + plateNumber + "\"}";
            LogHelper.Info(data, "无感主动缴费");
            WeChatParking.Core.Payment.UnionPay.BillInfo res = new WeChatParking.Core.Payment.UnionPay.BillInfo();
            try
            {
                bool isSign = WeChatParking.Core.Payment.UnionPay.UnionPayCommon.CheckSign(data, WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey, signature);
                if (isSign)
                {
                    //查询出费用
                    // 返回BillInfo实体
                    int fee = 0;
                    string sql = String.Format("carBrand ='{0}' AND status=1 ", plateNumber);
                    var bll = new Core.BLL.CarRecord();
                    var model = bll.Get(sql, "inTime", true).FirstOrDefault();
                    if (model == null)
                    {
                        res.resultCode = "1007";
                        res.message = "车辆不在场内";
                        return Content(JsonConvert.SerializeObject(res));
                    }
                    else
                    {
                        Core.BLL.ServerCode serverbll = new Core.BLL.ServerCode();
                    //是否已经下发过计费
                    ConsoleColor: var FeeQuery = serverbll.GetFeeQuery(String.Format(" Guid='{0}' and create_time>='{1}'", model.Guid, DateTime.Now.AddMinutes(-2)));
                        if (FeeQuery == null)
                        {
                            var feeModel = new Entity.Api.FeeQuery()
                             {
                                 Car_plate = model.carBrand,
                                 Time = DateTime.Now.ToString("yyyyMMddHHmm"),
                                 Guid = model.Guid,
                                 DeviceClient_code = model.retain2,
                                 EnterpriseID = model.Enterprise_ID,
                                 CCEnterpriseName = model.Enterprise_Name,
                                 State = 1
                             };
                            //下发计费查询指令
                            serverbll.AddFeeQuery(feeModel);
                            string code = "";
                            bool isOK = TcpServerController.Send(WeChatParking.Core.TCPServer.SendDatas.zhuDongFeeQuery(feeModel, ref code), code);
                            if (isOK)
                                serverbll.UpdateFeeQuery(feeModel.Guid, 2);
                            System.Threading.Thread.Sleep(1000);
                            goto ConsoleColor;
                        }
                        else
                        {
                            if (FeeQuery.State == 3)
                            {
                                fee = Convert.ToInt32(FeeQuery.Fee * 100);
                            }
                            else
                            {
                                System.Threading.Thread.Sleep(1000);
                                goto ConsoleColor;
                            }
                        }
                        var carModel = new Core.BLL.Car_Plate().Get(String.Format("Car_plate='{0}'", plateNumber), "").FirstOrDefault();
                        if (carModel == null)
                        {
                            res.resultCode = "1007";
                            res.message = "无用户绑定该车";
                            return Content(JsonConvert.SerializeObject(res));
                        }
                        var order = new Core.BLL.PrepaidOrder().CreateOrder(carModel.Wx_userId, model.id, FeeQuery.Fee, "");
                        var parking = new Core.BLL.Enterprise().Get(model.Enterprise_Code);
                        var en = new Core.BLL.Enterprise().Get(model.Enterprise_Code);
                        if (order == null || parking == null || en == null)
                        {
                            res.resultCode = "1003";
                            res.message = "系统异常";
                            return Content(JsonConvert.SerializeObject(res));
                        }
                        WeChatParking.Core.Payment.UnionPay.BillInfoData bill = new Core.Payment.UnionPay.BillInfoData();
                        bill.syncId = Guid.NewGuid().ToString("N");
                        bill.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
                        bill.industryCode = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayIndustryCode;
                        bill.plateNumber = model.carBrand;
                        bill.orderId = order.order_id;
                        bill.payAmount = fee;
                        bill.serviceAmount = fee;
                        bill.orderDate = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ");
                        bill.startTime = model.inTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ");
                        bill.endTime = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.sssZ");
                        bill.parkId = parking.ID.ToString();
                        bill.parkName = parking.Enterprise_Name;
                        bill.payCallback = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayCallback;
                        bill.accSplitData = en.accSplitData;
                        res.data = new List<Core.Payment.UnionPay.BillInfoData>() { bill };
                        res.resultCode = "0000";
                        res.message = "成功";
                        string qu = JsonConvert.SerializeObject(res);
                        LogHelper.Info(qu, "无感主动查询费用返回");
                        return Content(JsonConvert.SerializeObject(res));
                    }
                }
                else
                {
                    res.resultCode = "1005";
                    res.message = "签名失败";
                    string qu = JsonConvert.SerializeObject(res);
                    LogHelper.Info(qu, "无感主动查询费用返回");
                    return Content(qu);
                }

            }
            catch (Exception ex)
            {
                res.resultCode = "1003";
                res.message = "系统异常";
                LogHelper.Error(ex, "无感主动缴费");
                return Content(JsonConvert.SerializeObject(res));
            }
        }
        #endregion
        #region 停车场  通过
        /// <summary>
        /// 用户通过此功能查询停车场的剩余车辆状态
        /// </summary>
        /// <param name="appId">运营商给智慧通行平台颁发的商户号。</param>
        /// <param name="parkId">由运营商分配给停车场的Id</param>
        /// <param name="signature"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult queryParking(string appId, string parkId, string signature)
        {
            LogHelper.Info(String.Format("appId={0}&parkId={1}&signature={2}", appId, parkId, signature), "无感查询停车场状态");
            //查询出停车场的状态信息
            // 返回Parking实体
            WeChatParking.Core.Payment.UnionPay.Parking res = new WeChatParking.Core.Payment.UnionPay.Parking();
            try
            {
                Dictionary<String, String> paramDic = new Dictionary<string, string>();
                paramDic.Add("appId", appId);
                paramDic.Add("parkId", parkId);
                bool isSign = WeChatParking.Core.Payment.UnionPay.UnionPayCommon.CheckSign(JsonConvert.SerializeObject(paramDic), WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayKey, signature);
                if (isSign)
                {
                    var parModel = new Core.BLL.ParkingInfo().Get(int.Parse(parkId));
                    if (parModel != null)
                    {
                        res.resultCode = "0000";
                        res.message = "成功";
                        Core.Payment.UnionPay.ParkingInfo par = new Core.Payment.UnionPay.ParkingInfo();
                        par.appId = WeChatParking.Core.Payment.WeixinPay.WxpayConfig.UnionPayAppId;
                        par.parkId = parModel.parkId.ToString();
                        par.parkName = parModel.parkName;
                        par.lat = parModel.lat;
                        par.lon = parModel.lon;
                        par.capacityStatus = parModel.capacityStatus;
                        par.totalSpace = parModel.totalSpace;
                        par.freeSpace = parModel.freeSpace;
                        par.businessHours = parModel.businessHours;
                        par.cityName = parModel.cityName;
                        par.provinceName = parModel.provinceName;
                        par.districtName = parModel.districtName;
                        par.chargingDescription = parModel.chargingDescription;
                        par.updateTime = parModel.updateTime;
                        res.data = par;
                    }
                    else
                    {
                        res.resultCode = "1007";
                        res.message = "车场id错误;";
                    }
                }
                else
                {
                    res.resultCode = "1004";
                    res.message = "签名失败;";
                }

            }
            catch (Exception ex)
            {
                res.resultCode = "1003";
                res.message = "系统异常";
                LogHelper.Error(ex, "无感主动停车场");

            }
            return Content(JsonConvert.SerializeObject(res));
        }
        #endregion
        #region 健康状态  通过
        /// <summary>
        /// 智慧通行平台通过此接口检查停车场系统是否处于活动状态
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult queryHealth()
        {
            WeChatParking.Core.Payment.UnionPay.Responses res = new WeChatParking.Core.Payment.UnionPay.Responses();
            res.resultCode = "0000";
            res.message = "成功";
            return Content(JsonConvert.SerializeObject(res));
        }
        #endregion
    }
}
